import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Input,
  Table,
  Button,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { TableListParams } from './data';

const { pathname } = window.location;

interface PostChargesListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  screen: string;
}

interface PostChargesListState {
  rowId:number;
  searchValues: TableListParams;
}

@connect(({
  PostChargesList: { dataInfo },
  global: { screen },
  loading,
}: any) => ({
  dataInfo,
  screen,
  loading: loading.effects['PostChargesList/fetch'],
}))

class PostChargesListElem extends React.Component<PostChargesListProps, PostChargesListState> {
  columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '套餐名称',
      dataIndex: 'name',
      align: 'center',
      width: 120,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            style={{ maxWidth: '90%' }}
            onClick={() => this.handleEditPostCharges(record.id, record.name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '免费时间',
      children: [
        {
          title: '投递',
          dataIndex: ['columns', 'detention_normal_time'],
          align: 'center',
        },
        {
          title: '滞留件',
          dataIndex: ['columns', 'normal_time'],
          align: 'center',
        },
      ],
    },
    {
      title: '常规价格',
      children: [
        {
          title: '投递',
          dataIndex: ['columns', 'use'],
          align: 'center',
        },
        {
          title: '用户取件',
          dataIndex: ['columns', 'user_use'],
          align: 'center',
          width: 100,
        },
      ],
    },
    {
      title: '超时价格',
      children: [
        {
          title: '投递',
          dataIndex: ['columns', 'detention_price'],
          align: 'center',
        },
        {
          title: '滞留件',
          dataIndex: ['columns', 'overtime_price'],
          align: 'center',
        },
      ],
    },
    {
      title: '价格限制',
      dataIndex: ['columns', 'limit'],
      align: 'center',
      width: 100,
    },
    {
      title: '柜体积分',
      dataIndex: ['columns', 'credit'],
      align: 'center',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      render: (val: number) => (
        <span>{val === 1 ? '有效' : '无效'}</span>
      ),
    },
    {
      title: '操作',
      align: 'center',
      render: (text: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleEditPostCharges(record.id, record.name)}
          >
            编辑
          </span>
        </div>
      ),
    },
  ];

  state: PostChargesListState = {
    rowId: 0,
    searchValues: {
      name: '',
      pageIndex: 1,
      pageSize: 20,
    },
  }

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        pageIndex: Number(pageIndex) || 1,
        pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
      },
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const {
      searchValues: { pageIndex, pageSize, ...values },
    } = this.state;
    const params = { ...values };

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  }

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  }

  getQueryParams = () => {
    const { searchValues } = this.state;
    return searchValues;
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站资费配置',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const query = {
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '驿站资费配置',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站资费配置',
      url: pathname,
      isTopMenu: true,
    });
  }

  /**
   * 新建套餐
   */
  handleAddPostCharges = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建套餐',
      url: '/charges/postCharges/list/add',
    });
  }

  /**
   * 编辑套餐
   */
  handleEditPostCharges = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/charges/postCharges/list/edit?id=${id}`,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('importInfo') >= 0
      ? typeName : `PostChargesList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="资费名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddPostCharges}
            >
              新建套餐
            </Button>
          </div>

          <Table
            rowKey="id"
            tableLayout="fixed"
            columns={this.columns}
            className="statementTable tableHeight60"
            dataSource={dataSource}
            pagination={pagination}
            bordered
            loading={loading}
            scroll={{ x: 1100 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </>
    );
  }
}

export default Form.create<PostChargesListProps>()(PostChargesListElem);
